<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>WebGL Full-Screen Rectangle without varying</title>
  <style>
    canvas {
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>
<canvas id="canvasWebgl" width="500" height="500"></canvas>

<!-- 顶点着色器 -->
<script id="vertex-shader" type="x-shader/x-vertex">
        attribute vec2 a_position;
        void main(){
            // 将顶点位置归一化到[-1, 1]范围
            gl_Position = vec4(a_position, 0.0, 1.0);
        }
    </script>

<!-- 片元着色器 -->
<script id="fragment-shader" type="x-shader/x-fragment">
        precision mediump float;
        uniform vec2 u_resolution;

        void main(){
            // 获取归一化的片段坐标
            vec2 st = gl_FragCoord.xy / u_resolution;
            // 设置颜色为片段坐标的x和y值
            gl_FragColor = vec4(st.x, st.y, 0.0, 1.0);
        }
    </script>

<script>
  // 获取WebGL上下文
  const canvas = document.getElementById('canvasWebgl');
  const gl = canvas.getContext('webgl');

  if (!gl) {
    alert('WebGL not supported');
    throw new Error('WebGL not supported');
  }

  // 创建着色器
  function createShader(gl, type, source) {
    const shader = gl.createShader(type);
    gl.shaderSource(shader, source);
    gl.compileShader(shader);
    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
      console.error('Shader compile failed:', gl.getShaderInfoLog(shader));
      gl.deleteShader(shader);
      return null;
    }
    return shader;
  }

  const vertexShaderSource = document.getElementById('vertex-shader').innerText;
  const fragmentShaderSource = document.getElementById('fragment-shader').innerText;

  const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
  const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);

  // 创建程序并链接着色器
  const program = gl.createProgram();
  gl.attachShader(program, vertexShader);
  gl.attachShader(program, fragmentShader);
  gl.linkProgram(program);

  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
    console.error('Program link failed:', gl.getProgramInfoLog(program));
    gl.deleteProgram(program);
    throw new Error('Program link failed');
  }

  gl.useProgram(program);

  // 获取uniform位置
  const uResolutionLocation = gl.getUniformLocation(program, 'u_resolution');

  // 定义顶点数据 (全屏矩形)
  const positions = new Float32Array([
    -1, -1,  // 左下角
    1, -1,  // 右下角
    -1,  1,  // 左上角
    1,  1   // 右上角
  ]);

  const positionBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);

  // 获取attribute位置并启用
  const aPositionLocation = gl.getAttribLocation(program, 'a_position');
  gl.enableVertexAttribArray(aPositionLocation);
  gl.vertexAttribPointer(aPositionLocation, 2, gl.FLOAT, false, 0, 0);

  // 传递画布的分辨率到片元着色器
  gl.uniform2f(uResolutionLocation, canvas.width, canvas.height);

  // 绘制两个三角形以组成一个矩形
  gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
</script>
</body>
</html>